package com.mg.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mg.common.Constants;
import com.mg.dto.PresentRecordDto;
import com.mg.dto.SimpleResult;
import com.mg.mapper.PresentRecordMapper;
import com.mg.mapper.UserMapper;
import com.mg.model.PresentRecord;
import com.mg.model.User;
import com.mg.service.PresentRecordService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by mg1213 on 2018/3/18.
 */
@Service
public class PresentRecordServiceImpl implements PresentRecordService {
    @Autowired
    private PresentRecordMapper presentRecordMapper;
    @Autowired
    private UserMapper userMapper;

    private Logger logger = LogManager.getLogger(PresentRecordServiceImpl.class.getName());

    @Override
    public PageInfo<PresentRecordDto> selectPageInfo(PresentRecordDto presentRecordDto, int start, int limit) {
        PageHelper.offsetPage(start, limit);
        if (presentRecordDto.getState() != null && Constants.ALL_STRING.equals(presentRecordDto.getState())) {
            presentRecordDto.setState(null);
        }
        List<PresentRecordDto> resultList = presentRecordMapper.selectPageInfo(presentRecordDto);
        PageInfo<PresentRecordDto> result = new PageInfo<>(resultList);
        return result;
    }

    @Override
    public SimpleResult insertPresentRecord(PresentRecord record) {
        SimpleResult result = new SimpleResult();
        try {
            record.setPresentTime(new Date());
            record.setFinish(0);
            User user= new User();
            user.setId(record.getUserId());
            user=userMapper.selectOne(user);
            BigDecimal frozeMoney=user.getFrozeMoney();
            BigDecimal effctiveMoney=user.getBalance().subtract(frozeMoney);
            if(effctiveMoney.compareTo(record.getAmount())<0){
                result.setSuccess(false);
                result.setMsg("可用余额不足");
                return  result;
            }
            BigDecimal balance=user.getBalance();
            frozeMoney=frozeMoney.add(record.getAmount());
            user=new User();
            user.setId(record.getUserId());
            user.setFrozeMoney(frozeMoney);
            userMapper.updateByPrimaryKeySelective(user);
            user.setBalance(balance);
            result.setObject(user);
            presentRecordMapper.insert(record);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("新增提现信息失败 系统未知异常");
            logger.error("新增提现信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult updatePresentRecord(PresentRecord record) {
        SimpleResult result = new SimpleResult();
        try {
            PresentRecord record1 = new PresentRecord();
            record1.setId(record.getId());
            record1 = presentRecordMapper.selectOne(record1);
            if (record1 == null) {
                result.setSuccess(false);
                result.setMsg("该提现信息不存在，请刷新重试！");
            } else {
                if (Constants.PRESENT_SUCCESS.equals(record.getState()) && !record1.getState().equals(record.getState())) {
                    User user = new User();
                    user.setId(record1.getUserId());
                    user = userMapper.selectOne(user);
                    if (user == null) {
                        result.setSuccess(false);
                        result.setMsg("更新提现信息失败，用户信息不存在");
                        return result;
                    } else {
                        BigDecimal balance = user.getBalance();
                        if (balance == null) {
                            balance = new BigDecimal(0.00);
                        }
                        BigDecimal frozeMoney = user.getFrozeMoney();
                        frozeMoney=frozeMoney.subtract(record.getAmount());
                        balance = balance.subtract(record.getAmount());
                        user=new User();
                        user.setId(record1.getUserId());
                        user.setBalance(balance);
                        user.setUpdateTime(new Date());
                        user.setFrozeMoney(frozeMoney);
                        record.setFinish(Constants.FINISH);
                        userMapper.updateByPrimaryKeySelective(user);

                    }
                }
                if (Constants.PRESENT_SUCCESS.equals(record1.getState()) && !record1.getState().equals(record.getState())) {
                    User user = new User();
                    user.setId(record1.getUserId());
                    user = userMapper.selectOne(user);
                    if (user == null) {
                        result.setSuccess(false);
                        result.setMsg("更新提现信息失败，用户信息不存在");
                        return result;
                    } else {
                        BigDecimal frozeMoney = user.getFrozeMoney();
                        if (frozeMoney == null) {
                            frozeMoney = new BigDecimal(0.00);
                        }
                        frozeMoney = frozeMoney.subtract(record.getAmount());
                        user.setFrozeMoney(frozeMoney);
                        user.setUpdateTime(new Date());
                        record.setFinish(Constants.FINISH);
                        userMapper.updateByPrimaryKeySelective(user);

                    }
                }
                record.setUpdateTime(new Date());
                presentRecordMapper.updateByPrimaryKeySelective(record);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("更新提现信息失败 系统未知异常");
            logger.error("更新提现信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult deletePresentRecord(String ids) {
        SimpleResult result = new SimpleResult();
        try {
            String[] idArr = ids.split(",");
            for (String id : idArr) {
                PresentRecord record1 = new PresentRecord();
                record1.setId(Integer.parseInt(id));
                record1 = presentRecordMapper.selectOne(record1);
                if(Constants.PRESENT_ING.equals(record1.getState())){
                    User user = new User();
                    user.setId(record1.getUserId());
                    user = userMapper.selectOne(user);
                    BigDecimal frozeMoney = user.getFrozeMoney();
                    frozeMoney=frozeMoney.subtract(record1.getAmount());
                    user=new User();
                    user.setUpdateTime(new Date());
                    user.setId(record1.getUserId());
                    user.setFrozeMoney(frozeMoney);
                    userMapper.updateByPrimaryKeySelective(user);
                }
                presentRecordMapper.deleteByPrimaryKey(Integer.parseInt(id));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("删除提现信息失败 系统未知异常");
            logger.error("删除提现信息失败 系统未知异常", e);
        }
        return result;
    }
}
